package com.coolwalker.common.chain;

import com.coolwalker.common.domain.BizContext;

import java.util.ArrayList;
import java.util.List;

/**
 * 抽象的业务处理链
 */
public abstract class AbstractBizHandlerChain<T extends BizContext> implements BizHandler<T> {

    /**
     * 业务处理链集合
     */
    private List<BizHandler> handlerChain = new ArrayList<>();

    public AbstractBizHandlerChain() {}

    public AbstractBizHandlerChain addHandler(BizHandler handler) {
        handlerChain.add(handler);
        return this;
    }

    public void doHandlerChain(T context) {
        if(handlerChain == null || handlerChain.size() == 0) {
            return;
        }

        handlerChain.forEach(handler -> {
            if(handler.isHandler(context)) {
                return;
            }
            try {
                handler.doHandler(context);
            } catch (Exception e) {
                handler.handlerException(context, e);
            }
        });
    }

    @Override
    public boolean isHandler(BizContext context) {
        throw new UnsupportedOperationException("Not implement this isHandler method!!!");
    }

    @Override
    public void doHandler(BizContext context) {
        throw new UnsupportedOperationException("Not implement this handlerException method!!!");
    }

    @Override
    public void handlerException(BizContext context, Exception e) {
        throw new UnsupportedOperationException("Not implement this handlerException method!!!");
    }
}
